<?php
/**
 * Created by PhpStorm.
 * User: mj
 * Date: 17-6-7
 * Time: 下午6:20
 */

namespace App\Winged\Auth\Controllers;

use App\Winged\Auth\Administrator;
use App\Winged\Auth\Api\User;
use App\Winged\Auth\Backend\Api\Api;
use App\Winged\Auth\Consts\Roles;
use App\Winged\Auth\Permission;
use App\Winged\Auth\Repository\UserRepository;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class AuthController
{
    protected $user;

    public function __construct(UserRepository $user)
    {
        $this->user = $user;
    }

    /**
     * @router get /
     * @router get /admin/auth/login
     */
    public function getLogin()
    {
        $uuid = app()->tenant->getUuid() ;
        if (!Auth::guest() && app()->tenant->getUuid() === tenant()) {
            return redirect(config('admin.prefix'));
        }
        return view('admin::login',compact('uuid'));
    }

    /**
     * @router post /admin/auth/login
     */
    public function postLogin(Request $request)
    {
        $credentials = $request->only(['name', 'password','domain']);
        $validator   = Validator::make($credentials, [
            'name' => 'required', 'password' => 'required',
        ]);
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        }
        $domain = $request->input('domain',null);
        if ($domain != null) {
            $config = app()->tenant->getConfig($domain) ;
            if(app()->tenant->isCommonDomain() && is_null($config)){
                $errors = ['domain' => '域名'.$domain.'不存在'];
                return Redirect::back()->withInput()->withErrors($errors);
            }
            $tenant_id = $config ["tenant_uuid"];
        }
        else {
            if(app()->tenant->isCommonDomain()) {
                $errors = ['domain' => '请输入专属域名'];
                return Redirect::back()->withInput()->withErrors($errors);
            }
            $tenant_id = app()->tenant->getUuid();
        }
        $credentials ['username'] = $credentials['name'] ;
        $credentials ['rememberMe'] = true ;
        unset($credentials['name']);
        try{
            $token                    = \App\Winged\Auth\Api\Auth::login($credentials, $tenant_id);
            // 检查token以及tenant_id
            if ($token == null || $token == '' || $tenant_id == null || $tenant_id == '') {
                $errors = ['login' => '登录失败，请稍后重试'];
                return Redirect::back()->withInput()->withErrors($errors);
            }
            token(data_get($token, "access_token")); // 设置用户的登录token
            tenant($tenant_id);
            $info = User::info();
            // 检查用户是否有权限登录当前tenant
            if (count($info['properties']['roles']) == 0) {
                $errors = ['login' => '该用户无法登录，请联系管理员'];
                forget_session();
                return Redirect::back()->withInput()->withErrors($errors);
            }
            $info = $info->merge(['token' => $token]);
            // 设置Session数据
            user_id($info['id']); // 设置用户的登录id
            if(isset($info['doctor_info'])){
                department_id($info['doctor_info']['department_id']); // 存储department_id到session
            }
            // Auth login
            Auth::login(new Administrator($info->toArray()), false);            
            return redirect()->to(app()->tenant->loginRedirect($tenant_id));
        }catch (\Exception $e){
            $errors = ['login' => $e->getMessage()];
            return Redirect::back()->withInput()->withErrors($errors);
        }
    }

    public function getLogout()
    {
        $user_id = user_id();
        $tenant_id = tenant();
        Auth::logout();
        session()->forget('url.intented');
        forget_session();
        Redis::del("{$tenant_id}_{$user_id}_cookies");

        return redirect('/');
    }


    /**
     * @router /admin/auth/roles
     */
    public function roles()
    {
        return Admin::content(function (Content $content) {
            $roleHeader       = ['编号', '名称', '标志', 'visible'];
            $roles            = User::roles();
            $roleTable        = new Table($roleHeader, $roles->toArray());
            $permissions      = User::permissions();
            $permissionHeader = ['编号', '名称', '标志'];
            $permissionTable  = new Table($permissionHeader, $permissions->toArray());
            $tab              = new Tab();
            $tab->add('角色列表', $roleTable);
            $tab->add('权限列表', $permissionTable);
            $content->body($tab->render());
        });
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function users()
    {
        $users = $this->user->all();

        // 如果当前用户不是系统管理员，则隐藏掉用户列表里的系统管理员
        if (!Permission::isAdministrator()) {
            $doctors = $users['doctors'];
            for ($i = 0; $i < count($doctors); $i++) {
                $is_admin = false;
                for ($r = 0; $r < count($doctors[$i]['doctor_roles']); $r ++) {
                    if ($doctors[$i]['doctor_roles'][$r]['slug'] == Roles::MASTER_SUPERADMIN) {
                        $is_admin = true;
                        break;
                    }
                }
                if ($is_admin) {
                    unset($doctors[$i]);
                }
            }
            $users->put('doctors', array_values($doctors));
        }
        
        if (request()->wantsJson()) {
            return response()->json($users);
        }
        Auth::user()->requireBasicUserInfo(['properties.roles']);
        $roles            = User::roles();
		// 去掉系统管理员 - 不允许租户添加系统管理员角色
        if (!Permission::isAdministrator()) {
            for ($i = 0; $i < count($roles); $i++) {
                if ($roles[$i]['slug'] == Roles::MASTER_SUPERADMIN){
                    unset($roles[$i]);
                    break;
                }
            }
        }
        return Admin::content(function (Content $content) use ($users,$roles) {
            $view = view('winged.patients::auth.index', compact('users','roles'));
            $content->body($view);
        });
    }

    /**
     *      * 目前只可以更改用户权限和角色
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $user_id = $request->input('user_id');
        $roles   = (array)$request->input('roles');
        if (!Auth::user()->isAdministrator() && in_array(1, $roles)) {
            return response()->json([
                'status'  => 403,
                'message' => '非超级管理员用户不能更改管理员权限',
            ]);
        }
        $res = User::updateUserRolesAndPermissions(compact('user_id', 'roles', 'permissions'));
        return response()->json($res);
    }

    /**
     * 获取用户信息接口
     */
    public function info(Request $request)
    {
        $id   = $request->input('id');
        $info = User::doctorInfo($id);
        return response()->json($info);
    }

    /**
     * 添加用户 和权限 .
     * { phone:xxx,password:xxx,code:xxx,platform:xxx}
     *
     * @param \Illuminate\Http\Request $request
     */
    public function addUser(Request $request)
    {
        try {
            $username             = $request->input('username');
            $password             = $request->input('password');
            $department_id        = $request->input('department_id');
            $second_department_id = $request->input('second_department_id');
            $user_id              = $request->input('user_id', null); // 更新接口传user_id
            $roles                = (array)$request->input('roles');
            $name                 = $request->input('name');
            $tech_title           = $request->input('tech_title');
            if (is_null($user_id)) {
                $registerInfo = [
                    'user_id'       => user_id(),
                    'token'         => '',
                    'random'        => rand(1111, 9999),
                    'username'      => $username,
                    'password'      => $password,
                    'department_id' => $department_id,
                    'role'          => "0",//  0 医生   １患者   ２接待组
                ];
                $user         = User::resigter($registerInfo);
                if (!isset($user['id']) || $user ['id'] == null) {
                    return response()->json([
                        'msg' => '添加用户失败:' . $user['status']
                    ], 500);
                }
                $user_id = $user ['id'];
            }
            User::updateUserRoles(compact('user_id', 'roles')); // 直接过了，返回空字符串
            // 更新个人信息  tech_title  user_id name
            $updateInfo = [
                'name'                 => $name,
                'user_id'              => $user_id,
                'tech_title'           => $tech_title,
                'department_id'        => $department_id,
                'second_department_id' => $second_department_id,
            ];
            $res        = User::updateUserInfo($updateInfo);
            if ($res ['status'] === Api::SUCCESS) {
                return response()->json([
                    'msg' => '增加成功',
                ], 200);
            } else {
                return response()->json([
                    'msg' => '新增用户成功，更新用户信息失败',
                ], 500);
            }
        } catch (\Exception $e) {
            return response()->json([
                'msg' => $e->getMessage(),
            ], 500);
        }
    }


    public function reset()
    {
        return Admin::content(function (Content $content){
            $content->header('修改密码');
            $view = view('winged.patients::auth.reset');
            $content->body($view);
        });
    }


    public function resetPost(Request $request)
    {
        $data = [];
        $data ['phone'] = Auth::user()->getAttribute('username');
        $data ['old_pwd'] = $request->input('old_pwd',null);
        if(is_null($data ['old_pwd']))
        {
            return response()->json([
                'status' => '500',
                'msg'    => '密码不能为空',
            ]);
        }
        $data ['old_pwd'] = sha1($data['old_pwd']);
        $data ['new_pwd'] = $request->input('new_pwd');
        $data ['platform'] = 'doctor' ;
        $data ['rand'] = rand(1111,9999);
        $data ['user_id'] = user_id();
        $res = User::reset($data);
        if($res ['status'] == Api::SUCCESS)
        {
            $this->getLogout();
            return response()->json([
                'status' => '200',
            ]);
        }
        else{
            return response()->json([
                'status' => '500',
                'msg' => $res ['error_code'] ?? "",
            ]);
        }
    }

}
